/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import entities.Problem;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Contest;
import entities.Keyword;
import java.util.ArrayList;
import java.util.List;
import entities.Submission;
import entities.Testcase;
import exceptions.DatabaseException;

/**
 *
 * @author sbaldrich
 */
public class ProblemJpaController {

    public ProblemJpaController()
    {
        emf = Persistence.createEntityManagerFactory("CMalphaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Problem problem)
    {
        if (problem.getKeywordList() == null)
        {
            problem.setKeywordList(new ArrayList<Keyword>());
        }
        if (problem.getSubmissionList() == null)
        {
            problem.setSubmissionList(new ArrayList<Submission>());
        }
        if (problem.getTestcaseList() == null)
        {
            problem.setTestcaseList(new ArrayList<Testcase>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Contest contest = problem.getContest();
            if (contest != null)
            {
                contest = em.getReference(contest.getClass(), contest.getIdContest());
                problem.setContest(contest);
            }
            List<Keyword> attachedKeywordList = new ArrayList<Keyword>();
            for (Keyword keywordListKeywordToAttach : problem.getKeywordList())
            {
                keywordListKeywordToAttach = em.getReference(keywordListKeywordToAttach.getClass(), keywordListKeywordToAttach.getIdKeyword());
                attachedKeywordList.add(keywordListKeywordToAttach);
            }
            problem.setKeywordList(attachedKeywordList);
            List<Submission> attachedSubmissionList = new ArrayList<Submission>();
            for (Submission submissionListSubmissionToAttach : problem.getSubmissionList())
            {
                submissionListSubmissionToAttach = em.getReference(submissionListSubmissionToAttach.getClass(), submissionListSubmissionToAttach.getIdSubmission());
                attachedSubmissionList.add(submissionListSubmissionToAttach);
            }
            problem.setSubmissionList(attachedSubmissionList);
            List<Testcase> attachedTestcaseList = new ArrayList<Testcase>();
            for (Testcase testcaseListTestcaseToAttach : problem.getTestcaseList())
            {
                testcaseListTestcaseToAttach = em.getReference(testcaseListTestcaseToAttach.getClass(), testcaseListTestcaseToAttach.getIdTestCase());
                attachedTestcaseList.add(testcaseListTestcaseToAttach);
            }
            problem.setTestcaseList(attachedTestcaseList);
            em.persist(problem);
            if (contest != null)
            {
                contest.getProblemList().add(problem);
                contest = em.merge(contest);
            }
            for (Keyword keywordListKeyword : problem.getKeywordList())
            {
                keywordListKeyword.getProblemList().add(problem);
                keywordListKeyword = em.merge(keywordListKeyword);
            }
            for (Submission submissionListSubmission : problem.getSubmissionList())
            {
                Problem oldProblemOfSubmissionListSubmission = submissionListSubmission.getProblem();
                submissionListSubmission.setProblem(problem);
                submissionListSubmission = em.merge(submissionListSubmission);
                if (oldProblemOfSubmissionListSubmission != null)
                {
                    oldProblemOfSubmissionListSubmission.getSubmissionList().remove(submissionListSubmission);
                    oldProblemOfSubmissionListSubmission = em.merge(oldProblemOfSubmissionListSubmission);
                }
            }
            for (Testcase testcaseListTestcase : problem.getTestcaseList())
            {
                Problem oldProblemOfTestcaseListTestcase = testcaseListTestcase.getProblem();
                testcaseListTestcase.setProblem(problem);
                testcaseListTestcase = em.merge(testcaseListTestcase);
                if (oldProblemOfTestcaseListTestcase != null)
                {
                    oldProblemOfTestcaseListTestcase.getTestcaseList().remove(testcaseListTestcase);
                    oldProblemOfTestcaseListTestcase = em.merge(oldProblemOfTestcaseListTestcase);
                }
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Problem problem) throws IllegalOrphanException, NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Problem persistentProblem = em.find(Problem.class, problem.getIdProblem());
            Contest contestOld = persistentProblem.getContest();
            Contest contestNew = problem.getContest();
            List<Keyword> keywordListOld = persistentProblem.getKeywordList();
            List<Keyword> keywordListNew = problem.getKeywordList();
            List<Submission> submissionListOld = persistentProblem.getSubmissionList();
            List<Submission> submissionListNew = problem.getSubmissionList();
            List<Testcase> testcaseListOld = persistentProblem.getTestcaseList();
            List<Testcase> testcaseListNew = problem.getTestcaseList();
            List<String> illegalOrphanMessages = null;
            for (Submission submissionListOldSubmission : submissionListOld)
            {
                if (!submissionListNew.contains(submissionListOldSubmission))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Submission " + submissionListOldSubmission + " since its problem field is not nullable.");
                }
            }
            for (Testcase testcaseListOldTestcase : testcaseListOld)
            {
                if (!testcaseListNew.contains(testcaseListOldTestcase))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Testcase " + testcaseListOldTestcase + " since its problem field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (contestNew != null)
            {
                contestNew = em.getReference(contestNew.getClass(), contestNew.getIdContest());
                problem.setContest(contestNew);
            }
            List<Keyword> attachedKeywordListNew = new ArrayList<Keyword>();
            for (Keyword keywordListNewKeywordToAttach : keywordListNew)
            {
                keywordListNewKeywordToAttach = em.getReference(keywordListNewKeywordToAttach.getClass(), keywordListNewKeywordToAttach.getIdKeyword());
                attachedKeywordListNew.add(keywordListNewKeywordToAttach);
            }
            keywordListNew = attachedKeywordListNew;
            problem.setKeywordList(keywordListNew);
            List<Submission> attachedSubmissionListNew = new ArrayList<Submission>();
            for (Submission submissionListNewSubmissionToAttach : submissionListNew)
            {
                submissionListNewSubmissionToAttach = em.getReference(submissionListNewSubmissionToAttach.getClass(), submissionListNewSubmissionToAttach.getIdSubmission());
                attachedSubmissionListNew.add(submissionListNewSubmissionToAttach);
            }
            submissionListNew = attachedSubmissionListNew;
            problem.setSubmissionList(submissionListNew);
            List<Testcase> attachedTestcaseListNew = new ArrayList<Testcase>();
            for (Testcase testcaseListNewTestcaseToAttach : testcaseListNew)
            {
                testcaseListNewTestcaseToAttach = em.getReference(testcaseListNewTestcaseToAttach.getClass(), testcaseListNewTestcaseToAttach.getIdTestCase());
                attachedTestcaseListNew.add(testcaseListNewTestcaseToAttach);
            }
            testcaseListNew = attachedTestcaseListNew;
            problem.setTestcaseList(testcaseListNew);
            problem = em.merge(problem);
            if (contestOld != null && !contestOld.equals(contestNew))
            {
                contestOld.getProblemList().remove(problem);
                contestOld = em.merge(contestOld);
            }
            if (contestNew != null && !contestNew.equals(contestOld))
            {
                contestNew.getProblemList().add(problem);
                contestNew = em.merge(contestNew);
            }
            for (Keyword keywordListOldKeyword : keywordListOld)
            {
                if (!keywordListNew.contains(keywordListOldKeyword))
                {
                    keywordListOldKeyword.getProblemList().remove(problem);
                    keywordListOldKeyword = em.merge(keywordListOldKeyword);
                }
            }
            for (Keyword keywordListNewKeyword : keywordListNew)
            {
                if (!keywordListOld.contains(keywordListNewKeyword))
                {
                    keywordListNewKeyword.getProblemList().add(problem);
                    keywordListNewKeyword = em.merge(keywordListNewKeyword);
                }
            }
            for (Submission submissionListNewSubmission : submissionListNew)
            {
                if (!submissionListOld.contains(submissionListNewSubmission))
                {
                    Problem oldProblemOfSubmissionListNewSubmission = submissionListNewSubmission.getProblem();
                    submissionListNewSubmission.setProblem(problem);
                    submissionListNewSubmission = em.merge(submissionListNewSubmission);
                    if (oldProblemOfSubmissionListNewSubmission != null && !oldProblemOfSubmissionListNewSubmission.equals(problem))
                    {
                        oldProblemOfSubmissionListNewSubmission.getSubmissionList().remove(submissionListNewSubmission);
                        oldProblemOfSubmissionListNewSubmission = em.merge(oldProblemOfSubmissionListNewSubmission);
                    }
                }
            }
            for (Testcase testcaseListNewTestcase : testcaseListNew)
            {
                if (!testcaseListOld.contains(testcaseListNewTestcase))
                {
                    Problem oldProblemOfTestcaseListNewTestcase = testcaseListNewTestcase.getProblem();
                    testcaseListNewTestcase.setProblem(problem);
                    testcaseListNewTestcase = em.merge(testcaseListNewTestcase);
                    if (oldProblemOfTestcaseListNewTestcase != null && !oldProblemOfTestcaseListNewTestcase.equals(problem))
                    {
                        oldProblemOfTestcaseListNewTestcase.getTestcaseList().remove(testcaseListNewTestcase);
                        oldProblemOfTestcaseListNewTestcase = em.merge(oldProblemOfTestcaseListNewTestcase);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = problem.getIdProblem();
                if (findProblem(id) == null)
                {
                    throw new NonexistentEntityException("The problem with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Problem problem;
            try
            {
                problem = em.getReference(Problem.class, id);
                problem.getIdProblem();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The problem with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Submission> submissionListOrphanCheck = problem.getSubmissionList();
            for (Submission submissionListOrphanCheckSubmission : submissionListOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Problem (" + problem + ") cannot be destroyed since the Submission " + submissionListOrphanCheckSubmission + " in its submissionList field has a non-nullable problem field.");
            }
            List<Testcase> testcaseListOrphanCheck = problem.getTestcaseList();
            for (Testcase testcaseListOrphanCheckTestcase : testcaseListOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Problem (" + problem + ") cannot be destroyed since the Testcase " + testcaseListOrphanCheckTestcase + " in its testcaseList field has a non-nullable problem field.");
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Contest contest = problem.getContest();
            if (contest != null)
            {
                contest.getProblemList().remove(problem);
                contest = em.merge(contest);
            }
            List<Keyword> keywordList = problem.getKeywordList();
            for (Keyword keywordListKeyword : keywordList)
            {
                keywordListKeyword.getProblemList().remove(problem);
                keywordListKeyword = em.merge(keywordListKeyword);
            }
            em.remove(problem);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Problem> findProblemEntities()
    {
        return findProblemEntities(true, -1, -1);
    }

    public List<Problem> findProblemEntities(int maxResults, int firstResult)
    {
        return findProblemEntities(false, maxResults, firstResult);
    }

    private List<Problem> findProblemEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Problem.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Problem findProblem(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Problem.class, id);
        } finally
        {
            em.close();
        }
    }
    public Problem findProblem(String problemCode)throws Exception
    {
        EntityManager em = getEntityManager();
        try
        {
            Query q = em.createNamedQuery("Problem.findByProblemCode");
            q.setParameter("problemCode", problemCode);
            return (Problem)q.getSingleResult();
        }
        catch(Exception e)
        {
            throw new DatabaseException("ProblemJpaController.findProblem");
        }
        finally
        {
            em.close();
        }
    }

    public int getProblemCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Problem> rt = cq.from(Problem.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    
}
